package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/Report")
public class ReportController {

    @Reference
    ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){

        try {
            //calendar是操作日期，日历的一个类
            Calendar instance = Calendar.getInstance();

            //将当前时间向前便宜12个月
            instance.add(Calendar.MONTH,-12);

            List<String> list = new ArrayList<>();
            for(int i = 0;i < 12; i++){
                instance.add(Calendar.MONTH,1);
                //simpledataformat 日期格式化，然后将设置好的日期进行格式化，在添加到list中
                list.add(new SimpleDateFormat("YYYY-MM").format(instance.getTime()));
            }

            //查询12个月分别注册的人数
            List<Integer> list1 = reportService.getMemberReport(list);

            Map<String, Object> map = new HashMap<>();
            map.put("months",list);
            map.put("memberCount",list1);

            return new Result(true,"查询成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){

        try {
            List<Map<String, Object>> map = reportService.getSetmealReport();

            List<String> list = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : map) {
                String name = (String) stringObjectMap.get("name");
                list.add(name);
            }

            Map<String, Object> map1 = new HashMap<>();
            map1.put("setmealNames",list);
            map1.put("setmealCount",map);
            return new Result(true,"生成成功",map1);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"生成失败");
        }

    }


    @RequestMapping("/getBusinessReportData")
    public Map<String, Object> getBusinessReportData(){
        Map<String, Object> map = new HashMap<>();

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
        String format = simpleDateFormat.format(date);

        //查询今日新增用户
        Integer todayNewMember = reportService.todayNewMember(format);

        //查询总会员数
        Integer totalMember = reportService.totalMember();

        //查询本周新增会员数
        Integer thisWeekNewMember = reportService.thisWeekNewMember(format);

        //查询本月新增会员数
        Integer thisMonthNewMember = reportService.thisMonthNewMember();

        //查询今日预约数
        Integer todayOrderNumber = reportService.todayOrderNumber(format);

        //查询今日出游数
        Integer todayVisitsNumber = reportService.todayVisitsNumber(format);

        //查询本周预约数
        Integer thisWeekOrderNumber = reportService.thisWeekOrderNumber();

        //查询本周出游数
        Integer thisWeekVisitsNumber = reportService.thisWeekVisitsNumber();

        //本月预约数
        Integer thisMonthOrderNumber = reportService.thisMonthOrderNumber();

        //本月的出游数
        Integer thisMonthVisitsNumber = reportService.thisMonthVisitsNumber();

        //查询预约热门信息，前六条
        List<Map<String, Object>> list = reportService.hotSetmeal();

        map.put("reportDate",format);
        map.put("todayNewMember",todayNewMember);
        map.put("totalMember",totalMember);
        map.put("thisWeekNewMember",thisWeekNewMember);
        map.put("thisMonthNewMember",thisMonthNewMember);
        map.put("todayOrderNumber",todayOrderNumber);
        map.put("todayVisitsNumber",todayVisitsNumber);
        map.put("thisWeekOrderNumber",thisWeekOrderNumber);
        map.put("thisWeekVisitsNumber",thisWeekVisitsNumber);
        map.put("thisMonthOrderNumber",thisMonthOrderNumber);
        map.put("thisMonthVisitsNumber",thisMonthVisitsNumber);
        map.put("hotSetmeal",list);
        return map;
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try{
            //远程调用报表服务获取报表数据
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
            String format = simpleDateFormat.format(date);

            //查询今日新增用户
            Integer todayNewMember = reportService.todayNewMember(format);

            //查询总会员数
            Integer totalMember = reportService.totalMember();

            //查询本周新增会员数
            Integer thisWeekNewMember = reportService.thisWeekNewMember(format);

            //查询本月新增会员数
            Integer thisMonthNewMember = reportService.thisMonthNewMember();

            //查询今日预约数
            Integer todayOrderNumber = reportService.todayOrderNumber(format);

            //查询今日出游数
            Integer todayVisitsNumber = reportService.todayVisitsNumber(format);

            //查询本周预约数
            Integer thisWeekOrderNumber = reportService.thisWeekOrderNumber();

            //查询本周出游数
            Integer thisWeekVisitsNumber = reportService.thisWeekVisitsNumber();

            //本月预约数
            Integer thisMonthOrderNumber = reportService.thisMonthOrderNumber();

            //本月的出游数
            Integer thisMonthVisitsNumber = reportService.thisMonthVisitsNumber();

            //查询预约热门信息，前六条
            List<Map<String, Object>> list = reportService.hotSetmeal();

            //获得Excel模板文件绝对路径
            //file.separator这个代表系统目录中的间隔符，说白了就是斜线。
            String temlateRealPath = request.getRealPath("/template") +
                    File.separator + "report_template.xlsx";

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(format);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日出游数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周出游数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月出游数

            int rowNum = 12;
            for(Map map : list){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal)map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.toString());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            // 下载的数据类型（excel类型）
            response.setContentType("application/vnd.ms-excel");
            // 设置下载形式(通过附件的形式下载)
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return null;
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
        }

    }

}
